#include "server/model/offlinemessagemodel.hpp"
#include "db.h"
#include "public.hpp"
#include <cstring>

bool OfflineMsgModel::insert(int userid, std::string msg) {
    MySQL mysql;
    if (!mysql.connect()) {
        return false;
    }

    MYSQL* conn = mysql.getConnection();  // 确保你的 MySQL 类提供这个函数
    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) {
        return false;
    }

    const char* sql = "INSERT INTO offlinemessage(userid, msg) VALUES(?, ?)";
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        mysql_stmt_close(stmt);
        return false;
    }

    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));

    // 参数1：userid（int类型）
    bind[0].buffer_type = MYSQL_TYPE_LONG;
    bind[0].buffer = (void*)&userid;
    bind[0].is_null = 0;
    bind[0].length = 0;

    // 参数2：msg（二进制blob）
    unsigned long msg_len = msg.size();
    bind[1].buffer_type = MYSQL_TYPE_BLOB;
    bind[1].buffer = (void*)msg.data();
    bind[1].buffer_length = msg_len;
    bind[1].length = &msg_len;
    bind[1].is_null = 0;

    if (mysql_stmt_bind_param(stmt, bind) != 0) {
        mysql_stmt_close(stmt);
        return false;
    }

    bool success = (mysql_stmt_execute(stmt) == 0);
    mysql_stmt_close(stmt);
    return success;
}

void OfflineMsgModel::remove(int userid) {
	char sql[SQLMAXSIZE] = { 0 };
	sprintf(sql, "DELETE FROM offlinemessage WHERE userid=%d", userid);
	MySQL mysql;
	if (mysql.connect()) mysql.update(sql);
}

std::vector<std::string> OfflineMsgModel::query(int userid) {
    std::vector<std::string> vec;

    char sql[SQLMAXSIZE] = { 0 };
    sprintf(sql, "SELECT message FROM offlinemessage WHERE userid=%d", userid);

    MySQL mysql;
    if (mysql.connect()) {
        MYSQL_RES* res = mysql.query(sql);
        if (res != nullptr) {
            MYSQL_ROW row;
            unsigned long* lengths;

            while ((row = mysql_fetch_row(res)) != nullptr) {
                lengths = mysql_fetch_lengths(res);
                if (lengths) {
                    std::string msg(row[0], lengths[0]);  // ✅ 正确构造二进制字符串
                    vec.push_back(msg);
                }
            }
            mysql_free_result(res);
        }
    }
    return vec;
}
